<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/../include/apps/janus/vcard/VCard.php';

/**
 * A collection class for the VCard class.
 * (Borrowed from Leeds Met Repository Open Search)
 * @author Mike Taylor (m.j.taylor@leedsmet.ac.uk)
 *
 */
class VCardCollection implements IteratorAggregate
{
	/**
	 * Array of VCard objects
	 * @var array
	 */
	private $collection_ = array();
	
	/**
	 * Constructor for VCardCollection
	 * 
	 * @return void
	 */
	public function __construct()
	{
		$this->collection_ = array();
	}
	
	/**
	 * Get an Iterator for the collection that allows foreach functionality
	 * @return ArrayIterator
	 */
	public function getIterator()
	{
        return new ArrayIterator($this->collection_);
    }
	
	/**
	 * Adds an item to the collection
	 * @param VCard $vCard
	 * @return int
	 */
	public function add(VCard $vCard)
	{
		$this->collection_[] = clone $vCard;
		
		// Useful to returning the key of the added
		return key(end($this->collection_));
	}
	
	/**
	 * Removes the item with the specified key from the collection
	 * @param $key
	 * @return bool
	 */
	public function remove($key)
	{
		if (array_key_exists($key))
		{
			unset($this->collection_[$key]);
			return true;
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * Removes all items from the collection that match the specified VCard
	 *  
	 * @param VCard $vCard
	 * @param $strict If TRUE then the function will check the object references
	 * @return void
	 */
	public function removeMatches(VCard $vCard, $strict = false)
	{
		$keys = array_keys($this->collection_, $vCard, $strict);
		
		foreach ($keys as $key)
		{
			$this->remove($key);
		}
	}
	
	/**
	 * Checks whether a given vCard is in the collection or not
	 * 
	 * @param VCard $vCard
	 * @param $strict If TRUE then the function will check the object references
	 * @return bool
	 */
	public function matchVCard(VCard $vCard, $strict = false)
	{
		return in_array($vCard, $this->collection_, $strict);
	} 
	
	/**
	 * Returns the number of items in the collection
	 * @return int
	 */
	public function count()
	{
		return count($this->collection_);
	}
	
	/**
	 * Gets an array containing the values of the specified field from each
	 * vCard in the collection
	 * @param $fieldName
	 * @return array
	 */
	public function getFieldValues($fieldName)
	{
		$values = array();
		
		foreach ($this->collection_ as $vCard)
		{
			$fieldValue = $vCard->getFieldValue($fieldName);
			
			if (!is_null($fieldValue))
			{
				$values[] = $fieldValue;
			}
		}
		
		return $values;
	}
}
?>